package comxin.demo1.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {

    //该类中的方法都是静态的，直接用类名调用即可，不需要被实例化
    private JdbcUtils(){}

    /*
    静态代码执行加载一次后，下面的文件能直接用吧
     */
    static InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
    static Properties properties=new Properties();
    static{
        try {
            properties.load(is);
            Class.forName(properties.getProperty("driverClass"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Connetion
     * @return 如果返回null获取失败，反之亦然
     */
    public static Connection getConnection() {
        Connection conn=null;
        try {
            conn= DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  conn;
    }

    /**
     * 关闭Connection，Statement，ResultSet连接
     * @param conn
     * @param sta
     * @param re
     */
    public static  void close(Connection conn, Statement sta, ResultSet re){
        if (re!=null){
            try {
                re.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }if (sta!=null){
            try {
                sta.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭Connction和Statement
     * @param conn
     * @param sta
     */
    public static  void close(Connection conn, Statement sta){
        if (sta!=null){
            try {
                sta.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *关闭Connetion，PrepareStatement,ResultSet连接
     * @param conn
     * @param ps
     * @param re
     */
    public static  void close(Connection conn, PreparedStatement ps,ResultSet re){
        if (re!=null){
            try {
                re.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }if (ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
